package com.csx.micrometer.common.filter;

import com.csx.micrometer.common.config.MicrometerCoordinateProperties;
import com.csx.micrometer.common.util.StringUtil;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.config.MeterFilter;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通过该Filter添加公共的标签,注入到容器中即可生效
 * @author cuisongxu
 * @date 2022/11/20 20:29
 */
public class CommonTagsMeterFilter implements MeterFilter {

    private final MeterFilter meterFilter;

    private final MicrometerCoordinateProperties micrometerCoordinateProperties;

    public CommonTagsMeterFilter(MicrometerCoordinateProperties micrometerCoordinateProperties) {
        this.meterFilter = createMapFilter(CommonTagsPool.getCommonTagsMap());
        this.micrometerCoordinateProperties = micrometerCoordinateProperties;
    }

    private static MeterFilter createMapFilter(Map<String, String> tags) {

        List<Tag> tagList = tags.entrySet().stream()
                .map(entry -> Tag.of(entry.getKey(), StringUtil.getOrEmpty(entry.getValue())))
                .collect(Collectors.toList());
        Tags commonTags = Tags.of(tagList);
        return MeterFilter.commonTags(commonTags);
    }

    @NonNull
    @Override
    public Meter.Id map(@NonNull Meter.Id id) {
        return meterFilter.map(id);
    }

}
